package cn.jingyuan.swan.system.domain.sys.dao.mysql;

import cn.jingyuan.swan.cloud.dao.DaoException;
import cn.jingyuan.swan.cloud.dao.mybatisplus.AbstractMyBatisPlusCrudDao;
import cn.jingyuan.swan.system.domain.sys.dao.UserAccountDao;
import cn.jingyuan.swan.system.domain.sys.entity.Account;
import cn.jingyuan.swan.system.domain.sys.mapper.UserAccountMapper;
import cn.jingyuan.swan.system.enums.SysAccountTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Repository
public class UserAccountDaoMySql extends AbstractMyBatisPlusCrudDao<Account, Long> implements UserAccountDao {

    @Resource
    UserAccountMapper mapper;

    @Override
    public int updatePassword(Long userId, List<SysAccountTypeEnum> accountTypes, String password) {
        Account sysAccount = new Account();
        sysAccount.setCredential(password);
        sysAccount.setUpdateTime(new Date());

        LambdaQueryWrapper<Account> wrapper = this.queryWrapper()
            .in(Account::getIdentityType, accountTypes)
            .eq(Account::getUserId, userId);

        try {
            return mapper.update(sysAccount, wrapper);
        } catch (Exception e) {
            throw new DaoException(e);
        }
    }

    @Override
    public Account getBy(String identifier, SysAccountTypeEnum identityType) {
        LambdaQueryWrapper<Account> wrapper = this.queryWrapper()
            .eq(Account::getIdentityType, identifier)
            .eq(Account::getIdentityType, identityType.getValue());

        try {
            return mapper.selectOne(wrapper);
        } catch (Exception e) {
            throw new DaoException(e);
        }
    }

    @Override
    public Account getByAccount(String account) {
        LambdaQueryWrapper<Account> wrapper = this.queryWrapper()
            .eq(Account::getIdentityType, account);

        try {
            return mapper.selectOne(wrapper);
        } catch (Exception e) {
            throw new DaoException(e);
        }
    }

    @Override
    public List<Account> findByUserId(Long userId) {
        LambdaQueryWrapper<Account> wrapper = this.queryWrapper()
            .eq(Account::getUserId, userId);

        try {
            return mapper.selectList(wrapper);
        } catch (Exception e) {
            throw new DaoException(e);
        }
    }

    @Override
    public BaseMapper<Account> getMapper() {
        return this.mapper;
    }

}
